<template>
    <div>
        <el-table :data="filteredTableData" style="width: 100%">
            <el-table-column prop="studentname" label="学生姓名" width="180">
                <template #header>
                    <el-input v-model="studentname" size="small" placeholder="输入学生姓名搜索" v-if="roleType
                        !== 3" />
                </template>
            </el-table-column>
            <el-table-column prop="class" label="班级" width="180" :filters="classList" :filter-method="filterTag">
                <template #default="scope">
                    {{ scope.row.class.title }}
                </template>
            </el-table-column>
            <el-table-column label="综合评分">
                <template #default="scope">
                    <el-rate :model-value="getOverallRate(scope.row)" :colors="colors" allow-half disabled />
                </template>
            </el-table-column>
            <el-table-column label="评分进度" width="180">
                <template #default="scope">
                    <el-progress :percentage="getRateProgress(scope.row)" />
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-badge :value="getUnratedTagCount(scope.row)" class="unrated-tag-badge"
                        :hidden="getUnratedTagCount(scope.row) === 0">
                        <el-button size="small" type="primary" round @click="handleRate(scope.row)">评分</el-button>
                    </el-badge>
                </template>
            </el-table-column>
        </el-table>
        <el-drawer v-model="drawerShow" :size="drawerSize">
            <template #header>
                <h4>学员战力评分</h4>
            </template>
            <el-button type="primary" :icon="PieChart"
                @click="drawerSize = '80%'; innerDrawerShow = true">可视化分析</el-button>
            <el-divider />
            <el-alert type="info" show-icon>
                请为 {{ curStudent.studentname }} 点亮成功之路的每一颗星星
            </el-alert>
            <el-divider />
            <div v-for="item in tagList" :key="item._id">
                <div class="rate-item">
                    <div>{{ item.title }}</div>
                    <el-rate :model-value="getItemRate(item.title)" :colors="colors"
                        @change="handleRateChange($event, item.title)" allow-half tabindex="-1"
                        :disabled="roleType === 3" />
                </div>
                <el-divider />
            </div>
            <el-drawer v-model="innerDrawerShow" size="50%" :append-to-body="true" :before-close="handleClose">
                <template #header>
                    <h4>可视化分析</h4>
                </template>
                <student-chart :data="{ studentList, curStudent, tagList }" v-if="innerDrawerShow"></student-chart>
            </el-drawer>
        </el-drawer>
    </div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue'
import { PieChart } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

import axios from 'axios'
import { useRoute } from 'vue-router'

import useUserStore from '../../store/useUserStore'
const { user: { username, role: { roleType } } } = useUserStore()

const route = useRoute()

console.log(route)

import StudentChart from '../../components/student-manage/StudentChart.vue'

const studentList = ref([])

const studentname = ref(route.query.name || '')

const classList = ref([])

const tagList = ref([])

const colors = ref(['#99A9BF', '#F7BA2A', '#FF9900'])

const drawerShow = ref(false)

const drawerSize = ref('30%')

const innerDrawerShow = ref(false)

const curStudent = ref({})

onMounted(async () => {
    if (roleType === 3) {
        studentname.value = username
    }

    await Promise.all([getList(), getTags()])
    // 调用接口获取班级列表数据
    // getList()

    // 调用接口获取技术标签数据
    // getTags()
})

const filteredTableData = computed(() => studentList.value.filter(item => item.studentname.toLowerCase().includes(studentname.value.toLowerCase())))

const filterTag = (value, row) => {
    return row.class === value
}

const getList = async () => {
    var res = await axios.get('/adminapi/students')
    // console.log(res.data)
    if (res.data.length === 0) return
    studentList.value = res.data
    // 可以直接过滤出班级数据，减少一次接口请求
    classList.value = [...new Set(res.data.map(item => item.class.title))].map(item => ({
        "text": item,
        "value": item
    }))
}

const getTags = async () => {
    var res = await axios.get('/adminapi/tags')
    tagList.value = res.data
}

const handleRate = (student) => {
    // console.log(student)
    drawerShow.value = true
    curStudent.value = student
}

const handleRateChange = async (value, title) => {
    // console.log(value, title)

    const res = await axios.put(`/adminapi/students/${curStudent.value._id}`, {
        key: title,
        value: value
    })

    if (res.statusText === 'OK') {
        ElMessage({
            message: `${curStudent.value.studentname}的 ${title} 评分成功！`,
            type: 'success'
        })
        await getList()
    } else {
        ElMessage({
            message: '评分失败！',
            type: 'error'
        })
    }
}

const getItemRate = (title) => {
    return studentList.value.filter(item => item._id === curStudent.value._id)[0].score[title]
}

const getUnratedTagCount = ({ score }) => {
    return tagList.value.length - Object.keys(score).length
}

const getRateProgress = ({ score }) => {
    if (tagList.value.length === 0) return 0
    return Math.round(Object.keys(score).length * 100 / tagList.value.length)
}

const getOverallRate = ({ score }) => {
    const values = Object.values(score)
    let sum = values.reduce((accumulator, currentValue) => accumulator + currentValue, 0)
    return sum / values.length
}

const handleClose = () => {
    innerDrawerShow.value = false
    drawerSize.value = '30%'
}
</script>

<style lang="scss" scoped>
.rate-item {
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.unrated-tag-badge {
    margin-top: 10px;
    margin-right: 30px;
}
</style>